package com.dsl.controller;

import com.dsl.annotation.LoginRequired;
import com.dsl.entity.Comment;
import com.dsl.entity.DiscussPost;
import com.dsl.entity.Page;
import com.dsl.entity.User;
import com.dsl.service.*;
import com.dsl.utils.CommunityConstant;
import com.dsl.utils.CommunityUtil;
import com.dsl.utils.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 用户控制器类，访问用户个人信息页面
 * @Author dsl
 * @Date 2024/9/7 上午9:22
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    //文件上传路径
    @Value("${community.path.upload}")
    private String uploadPath;

    //域名
    @Value("${community.path.domain}")
    private String domain;

    //项目路径
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    //取当前用户
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private AttentionService attentionService;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${qiniu.bucket.header.url}")
    private String headerBucketUrl;

    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage(Model model){

        //上传文件名称
        String fileName = CommunityUtil.generateUUID();
        //设置响应信息
        StringMap policy = new StringMap();
        policy.put("returnBody", CommunityUtil.getJSONString(0));
        //生成上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600, policy);

        model.addAttribute("uploadToken", uploadToken);
        model.addAttribute("fileName", fileName);

        return "/site/setting";
    }

    //更新头像路径
    @PostMapping("/header/url")
    @ResponseBody
    public String updateHeaderUrl(String fileName){
        if(StringUtils.isBlank(fileName)){
            return CommunityUtil.getJSONString(1, "文件名不能为空!");
        }

        String url = headerBucketUrl + "/" + fileName;
        userService.updateHeader(hostHolder.getUser().getId(), url);

        return CommunityUtil.getJSONString(0);
    }

    /**
     * 上传头像
     * 已废弃，改用表单直接上传七牛云服务器
     * @param headerImage 头像图片类
     * @param model 前端model
     * @return 设置页面
     */
    @LoginRequired
    @PostMapping("/upload")
    @Deprecated
    public String uploadHeader(MultipartFile headerImage, Model model){
        if(headerImage == null){
            model.addAttribute("error", "未选择图片");
            return "/site/setting";
        }

        //避免文件同名导致覆盖
        //获取文件名，从文件名中获取文件后缀并保存
        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));//从最后一个.向后截取
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式错误");
            return "/site/setting";
        }

        //生成随机文件名
         fileName = CommunityUtil.generateUUID() + suffix;
        //确定文件上传路径
        File dest = new File(uploadPath + "/" + fileName);
        try {
            //存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发生异常", e); //抛出异常
        }

        //更新当前用户头像路径(Web访问路径，不是本地磁盘路径)
        //http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";
    }


    /**
     * 获取头像
     * 已废弃
     * @param fileName 头像图片文件名称
     * @param response 响应
     */
    @GetMapping("/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
        //服务器存放路径
        fileName = uploadPath + "/" + fileName;
        //解析文件后缀，格式
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);//JDK7的语法，有close方法的话在编译阶段自动加上finally关闭（要有close方法）
                ServletOutputStream os = response.getOutputStream();
                ){
            byte[] buffer = new byte[1024];
            int b = 0;
            while((b = fis.read(buffer)) != -1){
                os.write(buffer, 0 , b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败" + e.getMessage());
        }
    }

    //用户个人主页
    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model){

        User user = userService.getUserById(userId);
        if(user == null){
            throw new RuntimeException(("该用户不存在！"));
        }
        //用户
        model.addAttribute("user", user);
        //点赞数量
        int likeCount = likeService.getUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        //关注数量
        long attentionCount = attentionService.getAttentionCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("attentionCount", attentionCount);
        //粉丝数量
        long fansCount = attentionService.getFansCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("fansCount", fansCount);
        //是否已关注
        boolean hasAttentioned = false;
        if(hostHolder.getUser() != null){
            hasAttentioned = attentionService.hasAttentioned(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasAttentioned", hasAttentioned);

        return "/site/profile";

    }

    /**
     *  修改密码业务逻辑
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param model 前端model
     * @return 返回设置页面
     */
    @PostMapping("/updatePassword")
    public String updatePassword(String oldPassword, String newPassword, Model model){

        User user = hostHolder.getUser();
        Map<String, Object> map = userService.updatePassword(user.getId(), oldPassword, newPassword);
        if (map == null || map.isEmpty()) {
            return "redirect:/logout";
        } else {
            model.addAttribute("oldPasswordMsg", map.get("oldPasswordMsg"));
            model.addAttribute("newPasswordMsg", map.get("newPasswordMsg"));
            return "/site/setting";
        }
    }

}
